package com.fingard.dsp.bank.directbank.epay01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;

public class EPAY01BatPayRec extends EPAY01Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return d_BatPayRec(p_req1988);
	}

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return d_BatPayRec(p_req9188);
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return d_QryBatPayRec(p_req9198);
	}

	/**
	 * 批量代收付提交
	 * 
	 * @param p_reqBat
	 *            批量代收付请求对象
	 * @return 批量代收付响应对象
	 * @throws Exception
	 */
	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		retAts.reqSeqID = p_reqBat.reqBatchNO;

		try {
			while (p_reqBat.readRecord()) {
				JSONObject bizContent = new JSONObject();
				bizContent.put("businessDocumentCode", p_reqBat.readedDetail.attribute13);
				bizContent.put("businessId", p_reqBat.reqBatchNO + "_" + p_reqBat.readedDetail.askNumber);
				bizContent.put("businessType", "ATS");
				bizContent.put("businessSubType", p_reqBat.readedDetail.attribute17);
				

				String cardBookCode = p_reqBat.readedDetail.recAct;
				if (p_reqBat.reqHeader.isBatRec) {
					cardBookCode = p_reqBat.readedDetail.payAct;
				}
				//companyAccount,公司账号,0004取报文RecAct节点，根据公司账号查找第三方通道，若数据库没有配置，则通过router在找一遍
				String companyAccount = p_reqBat.readedDetail.payAct;
				if (p_reqBat.reqHeader.isBatRec) {
					companyAccount = p_reqBat.readedDetail.recAct;
				}
				
				String tradeType = "0014";
				if (p_reqBat.reqHeader.isBatRec) {
					tradeType = "0013";
				}
				bizContent.put("tradeType", tradeType);
				
				if("0".equals(p_reqBat.readedDetail.attribute18)){
					bizContent.put("thirdPartType", getBankConfig().getMapValueByKey("thirdPartType", companyAccount));
				}else{
					bizContent.put("thirdPartType", getBankConfig().getMapValueByKey("thirdPartType", p_reqBat.readedDetail.attribute18));

				}
				String bankCode = p_reqBat.readedDetail.recBankCode;
				if (p_reqBat.reqHeader.isBatRec) {
					bankCode = p_reqBat.readedDetail.payBankCode;
				}
				
				String FinalBankCode = getBankConfig().getMapValueByKey("BankCodeMapping", bankCode);
				if(FinalBankCode != "" || !FinalBankCode.isEmpty()){
					bankCode = FinalBankCode;
				}

				bizContent.put("bankCode", bankCode);
				bizContent.put("bankName", p_reqBat.readedDetail.recBankName);
				bizContent.put("bankAreaCode", p_reqBat.readedDetail.recArea);
				bizContent.put("bankAreaName", p_reqBat.readedDetail.recAreaName);
				bizContent.put("bankLocationCode", p_reqBat.readedDetail.cnapsCode);
				bizContent.put("bankLocationName", p_reqBat.readedDetail.recBankLocation);
				bizContent.put("certificateCode", p_reqBat.readedDetail.certNum);
				if (p_reqBat.reqHeader.isBatRec) {
					bizContent.put("bankName", p_reqBat.readedDetail.payBankName);
					bizContent.put("bankAreaCode", p_reqBat.readedDetail.payArea);
					bizContent.put("bankAreaName", p_reqBat.readedDetail.payAreaName);
					bizContent.put("bankLocationCode", p_reqBat.readedDetail.cnapsCode);
					bizContent.put("bankLocationName", p_reqBat.readedDetail.payBankLocation);
				}
				bizContent.put("currencyType", "156");
				bizContent.put("certificateType", "01");
				bizContent.put("certificateCode", p_reqBat.readedDetail.certNum);

				String cardType = "01";
				if (StringHelper.hasAnyChar(p_reqBat.readedDetail.cardType)) {
					if ("2".equals(p_reqBat.readedDetail.cardType)) {
						cardType = "01";
					} else if ("1".equals(p_reqBat.readedDetail.cardType)) {
						cardType = "02";
					} else {
						cardType = "03";
					}
				}
				bizContent.put("cardBookType", cardType);
				bizContent.put("cardBookCode", cardBookCode);
				String cardHolder = p_reqBat.readedDetail.recName;
				if (p_reqBat.reqHeader.isBatRec) {
					cardHolder = p_reqBat.readedDetail.payName;
				}
				bizContent.put("cardHolder", cardHolder);
				bizContent.put("customerMobile", "");
				String isPrivate = "1";
				if (!"1".equals(p_reqBat.readedDetail.isPrivate)) {
					isPrivate = "2";
				}
				bizContent.put("isPrivate", isPrivate);
				bizContent.put("money", p_reqBat.readedDetail.payAmount);
				bizContent.put("tradeName", "");
				bizContent.put("businessRemark", p_reqBat.readedDetail.memo);
				bizContent.put("deptCode", p_reqBat.readedDetail.attribute16);
				bizContent.put("tradeAdd", "");
				bizContent.put("channelCode", p_reqBat.readedDetail.attribute14);
				bizContent.put("subChannelCode", p_reqBat.readedDetail.attribute15);
				
				bizContent.put("companyAccount", companyAccount);
				

				JSONObject tmpJsonRequest = new JSONObject();
				tmpJsonRequest.put("msgTopic", getBankConfig().getSetValue("topic", "", "trans"));
				tmpJsonRequest.put("msgTag", "ATS");
				tmpJsonRequest.put("platformType", "FMS");
				tmpJsonRequest.put("msgKey", "ATS" + "_" + p_reqBat.reqBatchNO + "_" + p_reqBat.readedDetail.askNumber);
				tmpJsonRequest.put("msgContent", bizContent);
				tmpJsonRequest.put("systemType", "GH");

				String tmpStrReq = JSON.toJSONString(tmpJsonRequest);

				try {
					sendDataToBank(tmpStrReq);
				} catch (Exception ex) {
					ex.printStackTrace();
					WriteBankLogLn(ex);
					continue;
				}
			}

			retAts.respCode = "0";
			retAts.respInfo = "批次提交成功";
			retAts.transState = "I4001";
			retAts.payInfoCode = "I4001";
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetToATS();
		return retAts;
	}

	/**
	 * 批量代收付状态查询
	 * 
	 * @param p_reqQryBat
	 * @return
	 * @throws Exception
	 */
	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		retAts.reqSeqID = p_reqQryBat.reqBatchNO;

		try {
			String localFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + p_reqQryBat.reqBatchNO + ".txt";
			WriteBankLogLn("本机交易通知结果文件路径:" + localFilePath);
			File tmpLocalFile = new File(localFilePath);
			if (tmpLocalFile.exists()) {
				retAts.respCode = "0";
				retAts.respInfo = "处理完成";
				retAts.transState = "0000";
				retAts.payInfoCode = "0000";
				String tmpStrRet = FileHelper.readFileText(localFilePath, getCharset());
				WriteBankLogLn("本机通知结果文件内容:\r\n" + tmpStrRet);
				String[] tmpStrJson = tmpStrRet.split("\r\n");
				for (String s : tmpStrJson) {
					s = "[" + s + "]";
					JSONArray tmpRespArray = JSONArray.parseArray(s);
					for (int i = 0; i < tmpRespArray.size(); i++) {
						JSONObject tmpRespJson = tmpRespArray.getJSONObject(i);
						RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

						if (p_reqQryBat.reqHeader.transType.equals("1998")) {
							tmpRetDetail.recAct = tmpRespJson.getString("cardBookCode");
						} else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
							tmpRetDetail.payAct = tmpRespJson.getString("cardBookCode");
						}
						tmpRetDetail.postScript = tmpRespJson.getString("businessId").split("_")[1];
						tmpRetDetail.payAmount = tmpRespJson.getString("money");
						tmpRetDetail.result = tmpRespJson.getString("tradeState");
						if(tmpRespJson.containsKey("errorCode")){
							tmpRetDetail.payInfoCode = tmpRespJson.getString("tradeState") + "+" + tmpRespJson.getString("errorCode");
						}else{
							tmpRetDetail.payInfoCode = tmpRespJson.getString("tradeState");
						}

						
						//if("0003".equals(tmpRespJson.getString("tradeState")) && tmpRespJson.containsKey("otherInfo")){
							//JSONObject otherInfo =  JSONObject.parseObject(tmpRespJson.getString("otherInfo"));
								//tmpRetDetail.payInfoCode = tmpRespJson.getString("tradeState") + "+" + (otherInfo.getString("payBackType").isEmpty()?"FAIL":otherInfo.getString("payBackType"));
								//WriteBankLogLn("payBackType是否为空:\r\n" + (otherInfo.getString("payBackType").isEmpty()) + "   payBackType = " + otherInfo.getString("payBackType"));

						//}else{
							//tmpRetDetail.payInfoCode = tmpRespJson.getString("tradeState");
						//}
						tmpRetDetail.memo = tmpRespJson.getString("errorMessage");

						retAts.writeRetDetail(tmpRetDetail);
					}
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "本机通知结果文件不存在,请稍后查询!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}